"use client";

import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { useAuth } from "@/contexts/auth-context";

export default function RegisterPage() {
  const router = useRouter();
  const { register } = useAuth();
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string>("");
  const [success, setSuccess] = useState(false);

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault();
    setIsLoading(true);
    setError("");
    setSuccess(false);

    const formData = new FormData(event.currentTarget);
    
    try {
      await register({
        email: formData.get("email") as string,
        password: formData.get("password") as string,
        username: formData.get("username") as string,
      });

      setSuccess(true);
      // 2秒后跳转到登录页
      setTimeout(() => {
        router.push("/auth/login");
      }, 2000);

    } catch (error) {
      if (error instanceof Error) {
        setError(error.message);
      } else if (typeof error === 'string') {
        setError(error);
      } else {
        setError("注册失败，请稍后重试");
      }
      console.error('Registration error:', { error });
    } finally {
      setIsLoading(false);
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-b from-background to-muted/50">
      <div className="w-full max-w-md mx-auto p-6 space-y-8">
        {/* 返回按钮 */}
        <Link 
          href="/"
          className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
        >
          <ArrowLeft className="w-4 h-4 mr-2" />
          返回首页
        </Link>

        {/* 标题 */}
        <div className="space-y-2 text-center">
          <h1 className="text-3xl font-bold tracking-tight">创建账号 ✨</h1>
          <p className="text-muted-foreground">
            填写以下信息完成注册
          </p>
        </div>

        {/* 成功提示 */}
        {success && (
          <div className="p-3 text-sm text-green-600 bg-green-100 rounded-lg flex items-center gap-2">
            <span>✅</span>
            注册成功！正在跳转到登录页面...
          </div>
        )}

        {/* 注册表单 */}
        <form onSubmit={handleSubmit} className="space-y-6">
          <div className="space-y-4">
            <div className="space-y-2">
              <label htmlFor="username" className="text-sm font-medium">
                用户名 👤
              </label>
              <input
                id="username"
                name="username"
                type="text"
                required
                className="w-full px-3 py-2 border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/50"
                placeholder="请输入用户名"
              />
            </div>
            <div className="space-y-2">
              <label htmlFor="email" className="text-sm font-medium">
                邮箱地址 📧
              </label>
              <input
                id="email"
                name="email"
                type="email"
                required
                className="w-full px-3 py-2 border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/50"
                placeholder="请输入邮箱"
              />
            </div>
            <div className="space-y-2">
              <label htmlFor="password" className="text-sm font-medium">
                设置密码 🔒
              </label>
              <input
                id="password"
                name="password"
                type="password"
                required
                minLength={6}
                className="w-full px-3 py-2 border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/50"
                placeholder="请输入密码（至少6位）"
              />
            </div>
          </div>

          {/* 错误提示 */}
          {error && (
            <div className="p-3 text-sm text-destructive bg-destructive/10 rounded-lg">
              {error}
            </div>
          )}

          {/* 注册按钮 */}
          <button
            type="submit"
            disabled={isLoading || success}
            className="w-full py-2.5 text-sm font-medium text-primary-foreground bg-primary rounded-lg hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary/50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {isLoading ? (
              <span className="flex items-center justify-center gap-2">
                <span className="animate-spin">🔄</span>
                注册中...
              </span>
            ) : success ? (
              <span className="flex items-center justify-center gap-2">
                <span>✅</span>
                注册成功
              </span>
            ) : (
              <span className="flex items-center justify-center gap-2">
                <span>✨</span>
                注册
              </span>
            )}
          </button>

          {/* 登录链接 */}
          <div className="text-center text-sm">
            <span className="text-muted-foreground">
              已有账号？
            </span>
            {" "}
            <Link 
              href="/auth/login"
              className="font-medium text-primary hover:underline"
            >
              立即登录 👉
            </Link>
          </div>

          {/* 用户协议 */}
          <div className="text-center text-xs text-muted-foreground">
            注册即表示您同意我们的
            <Link href="/terms" className="text-primary hover:underline mx-1">
              服务条款
            </Link>
            和
            <Link href="/privacy" className="text-primary hover:underline mx-1">
              隐私政策
            </Link>
          </div>
        </form>
      </div>
    </div>
  );
} 